package cn.myapp.ipc_client;

import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import cn.myapp.ipc.IMusicPlayer;
import cn.myapp.ipc.Music;

public class MainActivity extends Activity implements OnClickListener {
	private ServiceConnection conn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		conn = new InnerServiceConnection();
		int flags = BIND_AUTO_CREATE;
		Intent intent = new Intent("cn.tedu.ipc.itnent.action.SERVER_SERVICE");
		bindService(intent, conn, flags);
		
		findViewById(R.id.btn_play).setOnClickListener(this);
		findViewById(R.id.btn_pause).setOnClickListener(this);
		findViewById(R.id.btn_get_current_position).setOnClickListener(this);
		findViewById(R.id.btn_get_duration).setOnClickListener(this);
		findViewById(R.id.btn_is_playing).setOnClickListener(this);
		findViewById(R.id.btn_get_music_list).setOnClickListener(this);
	}
	
	private IMusicPlayer player;
	
	private class InnerServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			player = IMusicPlayer.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_get_music_list:
			try {
				List<Music> data = player.getMusicList();
				for (Music music : data) {
					Log.i("cn.tedu.ipc", "music -> " + music);
				}
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			break;
		
		case R.id.btn_play:
			try {
				player.play();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			break;
		case R.id.btn_pause:
			try {
				player.pause();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			break;
		case R.id.btn_get_current_position:
//			try {
//				player.getCurrentPosition();
//			} catch (RemoteException e) {
//				e.printStackTrace();
//			}
			break;
		case R.id.btn_get_duration:
//			try {
//				player.getDuration();
//			} catch (RemoteException e) {
//				e.printStackTrace();
//			}
			break;
		case R.id.btn_is_playing:
			try {
				player.isPlaying();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			break;
		}
	}

}
